package com.example.nfc.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.nfc.MainActivity;
import com.example.nfc.ProgressDialog;
import com.example.nfc.R;
import com.example.nfc.barcodescan.android.CaptureActivity;
import com.example.nfc.barcodescan.common.Constant;
import com.example.nfc.base.BaseNfcActivity;
import com.example.nfc.dialog.AlertDialog;
import com.example.nfc.dialog.BaseDialog;
import com.example.nfc.server.Const;
import com.example.nfc.server.network.http.HttpException;
import com.example.nfc.server.request.CardRequest;
import com.example.nfc.server.request.DuiKa;
import com.example.nfc.server.response.Admin;
import com.example.nfc.server.response.CardInfo;
import com.example.nfc.server.response.PointResult;
import com.example.nfc.server.response.Respone;
import com.example.nfc.server.response.Result;
import com.example.nfc.server.utils.DateUtil;
import com.example.nfc.server.utils.LogUtil;
import com.example.nfc.server.utils.NLog;
import com.example.nfc.server.utils.Output;
import com.example.nfc.server.utils.json.JsonMananger;
import com.example.nfc.tools.CheckPermissionUtil;
import com.example.nfc.tools.ScannerKeyEventHelper;
import com.yanzhenjie.permission.Permission;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SellerActivity extends BaseNfcActivity implements ScannerKeyEventHelper.OnScanSuccessListener  {
    private ScannerKeyEventHelper mScannerKeyEventHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seller);
        ButterKnife.bind(this);
        mScannerKeyEventHelper = new ScannerKeyEventHelper(this);
        String uname = getData(Const.USERNAME,"");
        inflate = LayoutInflater.from(this);
        username.setText("当前登录:"+uname);
        String l = getData(Const.LOG_SELLER,"");
        if(!TextUtils.isEmpty(l)){
            log.setText(l);
        }
        initWebView();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        mScannerKeyEventHelper.analysisKeyEvent(event);
        return super.dispatchKeyEvent(event);
    } /**
     * 扫描成功回调
     * @param barcode
     */
    @Override
    public void onScanSuccess(String barcode) {
        if(!TextUtils.isEmpty(barcode)){
            print(true,"已扫码到二维码,内码编号为:"+barcode);
            kh.setText(barcode);
            addCard(barcode);
        }
    }
    private final int REQUEST_CHECK = 1023;
    private void addCard(String code){
        duiKa = new DuiKa();
        duiKa.setInner(code);
        duiKa.setUser_name(zh.getText().toString());
        request(REQUEST_CHECK);
    }

    private List<CardInfo> cardInfoList ;

    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.listBox)
    LinearLayout listBox;
    @Bind(R.id.list)
    LinearLayout list;
    private LayoutInflater inflate;
    private boolean check(CardInfo cardInfo){
        if(cardInfoList==null){
            return false;
        }
        for(CardInfo cardInfo1:cardInfoList){
            if(cardInfo1.getCard_inner().equals(cardInfo.getCard_inner())){
                return true;
            }
        }
        return false;
    }
    //显示已添加的卡片信息
    private void toPrintCardInfo() {
        if(cardInfoList==null||cardInfoList.size()==0){
            list.removeAllViews();
            img.setVisibility(View.VISIBLE);
            listBox.setVisibility(View.GONE);
            return;
        }
        img.setVisibility(View.GONE);
        listBox.setVisibility(View.VISIBLE);
        list.removeAllViews();
        int i = 0 ;
        for(CardInfo cardInfo1:cardInfoList){
            View view = inflate.inflate(R.layout.item, null);
            TextView title = view.findViewById(R.id.title);
            title.setText("卡号:"+cardInfo1.getCard_inner());
            ImageView remove = view.findViewById(R.id.remove);
            remove.setTag(i);
            remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int)v.getTag();
                    if(cardInfoList!=null&&cardInfoList.size()>position) {
                        cardInfoList.remove(position);
                    }
                    toPrintCardInfo();
                }
            });
            i++;
            list.addView(view);
        }

    }

    @OnClick(R.id.clear)
    public void clearClick(){
        log.setText("");
        putData(Const.LOG_SELLER,"");
    }
    @OnClick(R.id.logout)
    public void logoutClick(){
        request(LOG_SELLERIN_OUT);
    }

    @Bind(R.id.kh)
    TextView kh;
    @Bind(R.id.zh)
    EditText zh;
    @Bind(R.id.duika)
    Button duika;
    @OnClick(R.id.duika)
    public void duikaClick(){
        if(TextUtils.isEmpty(zh.getText().toString())){
            shortToast("请输入用户账号!");
            return;
        }
        if(TextUtils.isEmpty(kh.getText().toString())){
            shortToast("请将卡片放置在手机背面识别!");
            return;
        }
        duiKaList = new ArrayList<>();
        int uid = getData(Const.UID,0);
        for(CardInfo cardInfo:cardInfoList){
            DuiKa duiKa = new DuiKa();
            duiKa.setInner(cardInfo.getCard_inner());
            duiKa.setUser_name(zh.getText().toString());
            duiKa.setDuikaUid(uid);
            duiKaList.add(duiKa);
        }
        request(DUI_KA);
        ProgressDialog.show(SellerActivity.this,"批量兑卡中...");
    }

    @OnClick(R.id.remove)
    public void removeClick(){
        zh.setText("");
    }

    @Bind(R.id.username)
    TextView username;
    @Bind(R.id.log)
    TextView log;

    @Override
    protected void onDestroy() {
        putData(Const.LOG_SELLER,log.getText().toString());
        super.onDestroy();
    }

    private static final int LOG_SELLERIN_OUT = 1000;
    private static final int DUI_KA = 1001;
    private DuiKa duiKa;
    private List<DuiKa> duiKaList;
    @Override
    public Object doInBackground(int requestCode, String parameter) throws HttpException {
        switch (requestCode){
            case LOG_SELLERIN_OUT:
                return action.getLogoutRequest();
            case DUI_KA:
                return action.duikaRequest(duiKaList);
            case REQUEST_CHECK:
                return action.duikaCheckRequest(duiKa);
        }
        return super.doInBackground(requestCode, parameter);
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        super.onSuccess(requestCode, result);
        switch (requestCode){
            case LOG_SELLERIN_OUT:
                startActivityAndFinish(MainActivity.class);
                break;
            case DUI_KA:
                ProgressDialog.disMiss();
                Respone respone = (Respone)result;
                if(respone.getCode()==200){
                    print(true,respone.getMessage());
                    if(respone.getResult()!=null) {
                        for (Result result1 : respone.getResult()) {
                            print(true,result1.getCate_name()+"卡，编号:"+result1.getCardName()+",漆币"+result1.getPoint()+"分");
                        }
                    }
                    if(respone.getPoint_result()!=null){
                        for (PointResult result1 : respone.getPoint_result()) {
                            print(true, "本次兑"+result1.getCate_name()+"卡数量为"+result1.getCount()+"张");
                        }
                    }
                    print(true, "本次返漆币总分:"+respone.getAllpoint()+"分");
                    cardInfoList.clear();
                    cardInfoList=null;
                    toPrintCardInfo();
                    showTable(respone);
                }else{
                    print(false,respone.getMessage());
                }
                break;
            case REQUEST_CHECK:
                Respone ck = (Respone)result;
                if(ck.getCode()==200){
                    if(cardInfoList==null){
                        cardInfoList = new ArrayList<>();
                    }
                    CardInfo cardInfo = ck.getCard();
                    if(check(cardInfo)){
                        print(false,duiKa.getInner()+":卡片已存在批量兑卡列表中!");
                        return;
                    }
                    cardInfoList.add(cardInfo);
                    toPrintCardInfo();
                    print(true,duiKa.getInner()+":已加入批量兑卡列表");
                }else{
                    print(false,duiKa.getInner()+":"+ck.getMessage());
                }
                break;
        }
    }
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    private void print(boolean ok,String t){
        String date = DateUtil.format(new Date(),null);
        log.append(Output.formatText("["+date+"]->"+t+"\n",ok?getResources().getColor(R.color.colorPrimary):getResources().getColor(R.color.colorAccent)));
        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }



    @Override
    public void onFailure(int requestCode, int state, Object result) {
        super.onFailure(requestCode, state, result);
        switch (requestCode){
            case LOG_SELLERIN_OUT:
                break;
            case DUI_KA:
                ProgressDialog.disMiss();
                print(false,"网络错误,兑卡失败！");
                break;
        }
    }

    private Tag detectedTag;
    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        readCard(intent);
    }

    private AlertDialog alertDialog;
    private void readCard(Intent intent){
        String value = readNfcTag(intent);
        if(!TextUtils.isEmpty(value)){
            print(true,"已识别到卡片,内码编号为:"+value);
            kh.setText(value);
            addCard(value);
        }else{
            print(false,"已识别到卡片,但此卡片为白卡(空卡)");
            if(alertDialog==null){
                alertDialog = new AlertDialog(this);
                alertDialog.setTitle("此卡片为空卡");
                alertDialog.hideJihuo();
                alertDialog.setSubmitTxt("确定");
                alertDialog.setCancelTxt("关闭");
                alertDialog.setContent("此卡片为空卡，请与管理员确认");
                alertDialog.setOnResult(new BaseDialog.OnResult() {
                    @Override
                    public void onYes() {

                    }

                    @Override
                    public void onActive() {

                    }

                    @Override
                    public void onNo() {

                    }
                });
            }
            alertDialog.show(0, Gravity.CENTER);
        }
    }
    /**
     * 读取NFC标签文本数据
     */
    private String readNfcTag(Intent intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msgs[] = null;
            int contentSize = 0;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                    contentSize += msgs[i].toByteArray().length;
                }
            }
            try {
                if (msgs != null) {
                    NdefRecord record = msgs[0].getRecords()[0];
                    String textRecord = parseTextRecord(record);
                    return textRecord;
                }
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 解析NDEF文本数据，从第三个字节开始，后面的文本数据
     *
     * @param ndefRecord
     * @return
     */
    public static String parseTextRecord(NdefRecord ndefRecord) {
        /**
         * 判断数据是否为NDEF格式
         */
        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            //下面开始NDEF文本数据第一个字节，状态字节
            //判断文本是基于UTF-8还是UTF-16的，取第一个字节"位与"上16进制的80，16进制的80也就是最高位是1，
            //其他位都是0，所以进行"位与"运算后就会保留最高位
            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
            //3f最高两位是0，第六位是1，所以进行"位与"运算后获得第六位
            int languageCodeLength = payload[0] & 0x3f;
            //下面开始NDEF文本数据第二个字节，语言编码
            //获得语言编码
            String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
            //下面开始NDEF文本数据后面的字节，解析出文本
            String textRecord = new String(payload, languageCodeLength + 1,
                    payload.length - languageCodeLength - 1, textEncoding);
            return textRecord;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode== Activity.RESULT_OK){
            if(requestCode==REQUEST_CODE){
                if (data != null) {
                    String code = data.getStringExtra(Constant.CODED_CONTENT);
                    if(!TextUtils.isEmpty(code)) {
                        kh.setText(code);
                        addCard(code);
                    }else {
                        print(false,"扫描内容为空!");
                    }
                }
            }
        }
    }
    private static final int REQUEST_CODE = 1001 ;
    @OnClick(R.id.scan)
    public void scanClick(){
        CheckPermissionUtil.check(SellerActivity.this, new String[]{Permission.CAMERA}, new CheckPermissionUtil.AfterDo() {
            @Override
            public void doIt() {
                openC();
            }
        });
    }
    private void openC(){
        Intent intent = new Intent(this, CaptureActivity.class);
        intent.putExtra(CaptureActivity.EXTRA_IMAGE_TITLE,"扫描条码/二维码");
        intent.putExtra(CaptureActivity.EXTRA_IMAGE_TYPE,0);
        startActivityForResult(intent,REQUEST_CODE);
    }

    @Bind(R.id.web)
    WebView web;
    private void initWebView(){
        web.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        web.getSettings().setAllowUniversalAccessFromFileURLs(true);//允许跨域
        web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        web.getSettings().setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        web.getSettings().setSupportZoom(false);//是否可以缩放，默认true
        web.getSettings().setUseWideViewPort(false);//设置此属性，可任意比例缩放。大视图模式
        web.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        web.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                result.confirm();
                return true;
            }
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                android.app.AlertDialog.Builder b = new android.app.AlertDialog.Builder(mContext);
                b.setTitle("");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
                b.create().show();
                return true;
            }
        });
        web.loadUrl("file:///android_asset/index.html");
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                show();
//            }
//        },2000);
    }
    private void showTable(Respone respone){
        if(web.getVisibility()==View.GONE){
            web.setVisibility(View.VISIBLE);
        }
        final String json = JsonMananger.beanToJsonStr(respone);
        LogUtil.e("json",json);
        web.post(new Runnable() {
            @Override
            public void run() {
                web.loadUrl("javascript:showData('" + json + "');");
            }
        });
    }
    private void show(){
        if(web.getVisibility()==View.GONE){
            web.setVisibility(View.VISIBLE);
        }
        final String json = " {\"allfee\":50,\"allpoint\":5,\"code\":200,\"message\":\"批量兑卡成功!\"," +
                "\"mobile_phone\":\"\",\"nick_name\":\"欧阳\",\"pay_points\":\"75\"," +
                "\"point_result\":[{\"cate_name\":\"A\",\"count\":1,\"fee\":50,\"point\":5}]," +
                "\"result\":[{\"cardName\":\"NO368893758140\",\"cate_name\":\"A\"," +
                "\"inner\":\"NM000031\",\"out\":\"A-000027\",\"point\":5}],\"uid\":0}";
        web.post(new Runnable() {
            @Override
            public void run() {
                web.loadUrl("javascript:showData('" + json + "');");
            }
        });

    }
}
